package com.example.study_manger.control;

import com.example.study_manger.entity.ApplyPermission;
import com.example.study_manger.entity.Organization;
import com.example.study_manger.entity.Role;
import com.example.study_manger.entity.UserTb;
import com.example.study_manger.pojo.PageResult;
import com.example.study_manger.repository.ApplyPermissionRe;
import com.example.study_manger.repository.RoleRe;
import com.example.study_manger.repository.UserTbRe;
import com.example.study_manger.service.UserService;
import com.example.study_manger.tools.JwtUtil;
import com.example.study_manger.tools.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class UserControl {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleRe roleRe;
    @Autowired
    private UserTbRe userTbRe;
    @Autowired
    private ApplyPermissionRe applyPermissionRe;
    @PostMapping("/login")
    public R<Role> login(@RequestBody UserTb userTb){
        UserTb login = userService.login(userTb);
        if (login != null){
            String token= JwtUtil.generateToken(login.getUsername());
            Role role = login.getRole();
            return R.own(200,token,role);
        }
        ApplyPermission byUsername = applyPermissionRe.findByUsername(userTb.getUsername());
        if (byUsername != null){
            return R.fail("请等待管理员开通权限");
        }
        return R.fail("用户名或密码错误");
    }
    @PostMapping("/register")
    public R<ApplyPermission> register(@RequestBody ApplyPermission applyPermission){
        return R.success(userService.register(applyPermission));
    }
    @GetMapping("/isUserNameExist")
    public R<Boolean> isExist(@RequestParam String userName){
        return R.success(userService.getUsername(userName));
    }
    @GetMapping("/getUserInfo")
    public R<UserTb> getUserInfo(@RequestParam String userName){
        UserTb userInfo = userService.getUserInfo(userName);
        return R.success(userInfo);
    }

    /**
     * 修改或新增角色
     * @param role
     * @return
     */
    @PutMapping("/addRole")
    public R<Role> updateUserInfo(@RequestBody Role role){
        System.out.println(role);
        Role save = roleRe.save(role);
        return R.success(save);
    }

    /**
     * 角色分页条件查询
     * @param organizationId
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/roles")
    public R<PageResult> getRoles(@RequestParam(required = false) Long organizationId,
                                  @RequestParam int page, @RequestParam int size){
        if (organizationId == null || organizationId==0){
            Page<Role> all = roleRe.findAll(PageRequest.of(page - 1, size));
            return R.success(new PageResult(all.getContent(),all.getTotalElements()));
        }
        Organization organization = new Organization();
        organization.setId(organizationId);
        Page<Role> byOrganizationId = roleRe.findAllByOrganization(organization, PageRequest.of(page - 1, size));
        return R.success(new PageResult(byOrganizationId.getContent(),byOrganizationId.getTotalElements()));
    }
    @DeleteMapping("/roles/{id}")
    public R<Boolean> deleteRole(@PathVariable Long id){
       try {
           roleRe.deleteById(id);
           return R.success(true);
       }catch (Exception e){
           return R.fail("删除失败");
       }
    }

    /**
     * 获取当前机构未有的管理角色
     * @param organization
     * @return
     */
    @PostMapping("/roleName")
    public R<List<Role>> getRoleName(@RequestBody Organization organization){
        List<Role> byOrganization = roleRe.findByOrganization(organization);
        if(byOrganization.size()==3){
            return R.success(null);
        }
        List<Role> roleList =new ArrayList<>();
        Role role = new Role();
        role.setRoleName("admin");
        role.setDescription("机构管理员");
        roleList.add(role);
        Role role1 = new Role();
        role1.setRoleName("publish");
        role1.setDescription("发布人员");
        roleList.add(role1);
        Role role2 = new Role();
        role2.setRoleName("review");
        role2.setDescription("审核人员");
        roleList.add(role2);
        List<Role> filteredRoleList = roleList.stream()
                .filter(r -> !byOrganization.stream().anyMatch(o -> o.getRoleName().equals(r.getRoleName())))
                .collect(Collectors.toList());
        return R.success(filteredRoleList);
    }
    //机构下已有角色
    @PostMapping("/roleNameHave")
    public R<List<Role>> getRoleNameHave(@RequestBody Organization organization){
        List<Role> byOrganization = roleRe.findByOrganization(organization);
        return R.success(byOrganization);
    }
    @GetMapping("/getUser")
    public R<PageResult> getUser(@RequestParam(required = false) Long organizationId,
                                   @RequestParam int page,
                                   @RequestParam int size){
        if(organizationId==0 || organizationId==null){
            System.out.println(11);
            Page<UserTb> all = userService.findAll(PageRequest.of(page - 1, size));
            return R.success(new PageResult(all.getContent(),all.getTotalElements()));

        }else {
            //机构下的所有账号
            Page<UserTb> userByOrgId = userService.getUserByOrgId(organizationId, page, size);
            return R.success(new PageResult(userByOrgId.getContent(),userByOrgId.getTotalElements()));
        }

    }
    @PutMapping("/save")
    public R<UserTb> addUser(@RequestBody UserTb userTb){
        UserTb save = userTbRe.save(userTb);
        if (save!=null) return R.success(userTb);
        else {
            return R.fail("添加失败");
        }
    }
    @DeleteMapping("/{id}")
    public R<Boolean> deleteUser(@PathVariable Long id){
        try {
            userTbRe.deleteById(id);
           return R.success(true);
        }catch (Exception e){
            return R.fail("删除失败");
        }
    }
}
